//
//  FollowNumberDetailViewController.m
//  PlayBall
//
//  Created by Edward Zhang on 12-5-8.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "JddFollowNumberDetailViewController.h"
#import "JddCommonFunction.h"
#import "JddViewControllerManager.h"
#import "JddFollowNumberDetailCell.h"
#import "SBJson.h"

@interface JddFollowNumberDetailViewController ()

@end

@implementation JddFollowNumberDetailViewController

@synthesize charseId;
@synthesize realResult;
@synthesize lotnameLabel;
@synthesize LotNumberLabel;
@synthesize IssueNumLabel;
@synthesize BuyedIssueNumLabel;
@synthesize realResultArray;
@synthesize chaseStateLabel;
@synthesize listTable;

SHARED_VIEW_CONTROLLER_IMPLEMENT(JddFollowNumberDetailViewController);

-(IBAction)stopFollow:(id)sender{
    UIAlertView *alert =[[UIAlertView alloc] initWithTitle:APP_NAME
                                                   message:@"确定要终止追号吗？"
                                                  delegate:self
                                         cancelButtonTitle:@"确定"
                                         otherButtonTitles:@"取消", nil];
    [alert show];
    
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==0) {
        JddQueryStopFollowOperation *operation = [[JddQueryStopFollowOperation alloc] init];
        operation.ChaseID = charseId;
        operation.delegate = self;
        [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
    }
}

-(void)QueryStopFollowOperationResult:(NSData *)result{
    [JddCommonFunction setWaitingViewHidden:YES fromController:self];
    if (result) {
        if ([JddDataParser parseBuyResult:result]){
            [JddCommonFunction messageBoxWithMessage:[JddError sharedInstance].message];
            [self startQuery];
        }
        else {
            [JddCommonFunction messageBoxWithMessage:[JddError sharedInstance].message];
            [JddCommonFunction setWaitingViewHidden:YES fromController:self];
        }
        
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (followNumArray.count > 0) {
        return 2;
    }else{
        return 1;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30.0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    JddFollowNumberHeaderCell *cell = [JddFollowNumberHeaderCell getInstanceView];
    if (section == 0 && followNumArray.count > 0) {
        cell.Date.text = @"追号内容";
    }else{
        cell.Date.text = @"所追期号";
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 && followNumArray.count > 0) {
        return 50.0;
    }else {
        return 44.0;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0 && followNumArray.count > 0) {
        return [followNumArray count];
    }else {
        return [realResultArray count];
    }
    
}

-(void)QueryBuyHistoryDetailOperationResult:(NSData *)result{
    if (result) {
        NSString *resultString = [JddDataParser parseBuyHistoryDetailResult:result];
        if (resultString == nil) {
            [JddCommonFunction messageBoxWithMessage:[JddError sharedInstance].message];
        }else {
            [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_BUY_DETAIL_DIGITAL
                                                                 fromController:self
                                                                     withObject:resultString
                                                                    withObject2:nil];
        }
        
    }
}

-(void)OldQueryBuyHistoryDetailOperationResult:(NSData *)result{
    if (result) {
        NSString *resultString = [JddDataParser oldparseBuyHistoryDetailResult:result];
        if (resultString == nil) {
            [JddCommonFunction messageBoxWithMessage:[JddError sharedInstance].message];
        }else {
            [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_BUY_DETAIL_DIGITAL_OLD
                                                                 fromController:self
                                                                     withObject:resultString
                                                                    withObject2:nil];
        }
        
    }
}

-(void)SelectDetail:(NSString*)schemeId{
    NSString *datassID = [NSString stringWithFormat:@"%@",((JddFollowNumberHistoryViewController*)self.fromController).dataSourID];
    if([datassID isEqualToString:@"0"]){//老系统方案详情
        JddOldQueryBuyHistoryDetailOperation *operation = [[JddOldQueryBuyHistoryDetailOperation alloc] init];
        operation.SchemeId = [NSString stringWithFormat:@"%d",[schemeId intValue]];
        operation.delegate = self;
        [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
    }else{
        JddQueryBuyHistoryDetailOperation *operation = [[JddQueryBuyHistoryDetailOperation alloc] init];
        operation.SchemeId = schemeId;
        operation.DataSource = ((JddFollowNumberHistoryViewController*)self.fromController).dataSourID;
        operation.delegate = self;
        [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 && followNumArray.count > 0) {
        JddDigitalBuyItemCell *cell = [JddDigitalBuyItemCell getInstanceView];
        NSString *lotNumbers = [followNumArray objectAtIndex:indexPath.row];
        NSArray *lotArray = [lotNumbers componentsSeparatedByString:@":"];
        
        NSString *playTypeName = [lotArray objectAtIndex:0];
        NSString *lotNumber = [lotArray objectAtIndex:1];
        
        NSArray *balls = [lotNumber componentsSeparatedByString:@"+"];
        NSMutableString *redBall = [balls objectAtIndex:0];
        
        
        cell.playTypeName.text = playTypeName;
        if ([balls count]>1) {
            cell.number.text = redBall;
            cell.number2.text = [balls objectAtIndex:1];
        }else {
            cell.number.text = redBall;
            cell.number2.text = @"";
        }
        [cell.number setAutomaticallyAddLinksForType:0];
        [cell.number2 setAutomaticallyAddLinksForType:0];
        cell.delegate = self ;
        return cell;
    } else {
        JddFollowNumberDetailCell *cell = [JddFollowNumberDetailCell getInstanceView];
        NSDictionary *cellvalue = [realResultArray objectAtIndex:indexPath.row];
        //    NSString *idValue = [cellvalue objectForKey:@"ChaseSchemes"];
        cell.CountLabel.text = [NSString stringWithFormat:@"%d",[[cellvalue objectForKey:@"Count"] intValue]];
        cell.MultipleLabel.text = [NSString stringWithFormat:@"%d", [[cellvalue objectForKey:@"Multiple"] intValue]];
        cell.StateLabel.text =[cellvalue objectForKey:@"State"];
        cell.IssueLabel.text = [cellvalue objectForKey:@"Issue"];
        cell.Issue = [cellvalue objectForKey:@"SchemeID"];
        cell.delegate = self;
        return cell;
    }
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
   // [self.navigationItem setTitle:@"追号详情"];
        UILabel *customLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 30)];
        customLab.backgroundColor = [UIColor clearColor];
        [customLab setText:@"追号详情"];
        customLab.textAlignment = NSTextAlignmentCenter;
        [customLab setTextColor:[UIColor whiteColor]];
        customLab.font = [UIFont systemFontOfSize:19];
        self.navigationItem.titleView = customLab;
//        //self.navigationItem.hidesBackButton = YES;
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,0)];
    listTable.tableFooterView = v;
    [listTable setSeparatorColor:SeparatorLineColor];
    if (IOS7) {
        [listTable setSeparatorInset:UIEdgeInsetsZero];
    }
    
}

-(void)startQuery{
    [JddCommonFunction setWaitingViewHidden:NO fromController:self];

    JddQueryFollowNumberDetailOperation *operation2 = [[JddQueryFollowNumberDetailOperation alloc] init];
    operation2.delegate = self;
    operation2.ChaseID = charseId;
    operation2.DatasourceID = @"1";
    [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation2];
    
}

- (void) QueryFollowNumberDetailOperationResult:(NSData *)result{
    [JddCommonFunction setWaitingViewHidden:YES fromController:self];
    if (result) {
        realResult = [JddDataParser parsefollowNumberResult:result];
        [self reloadData];
    } else {
        [JddCommonFunction messageBoxWithMessage:[JddError sharedInstance].message];
    }
}

-(void)reloadData
{
    realResultArray = [[NSArray alloc] init];
    SBJsonParser *jsonparse = [[SBJsonParser alloc] init];
    UIButton *stopbutton = (UIButton*)[self.view viewWithTag:31];
    stopbutton.hidden = NO;
    NSDictionary *cellvalue = [jsonparse objectWithString:realResult];
    NSString *lotNumber = [cellvalue objectForKey:@"LotNumber"];
    realResultArray = [cellvalue objectForKey:@"item"];
    self.lotnameLabel.text = [cellvalue objectForKey:@"LotName"];
    
    NSString *swm = [[cellvalue objectForKey:@"StopWhenWinMoney"] stringValue];
    if([swm integerValue] <= 0){
        self.stopLbl.text = @"无";
    }else{
        self.stopLbl.text = [NSString stringWithFormat:@"单期中奖金额≥%@彩豆", swm];
    }
    
    if ([lotNumber rangeOfString:@"&"].location != NSNotFound) {
        followNumArray = (NSMutableArray *)[lotNumber componentsSeparatedByString:@"&"];
        [followNumArray removeLastObject];
    } else {
        self.LotNumberLabel.text =[cellvalue objectForKey:@"LotNumber"];
        [self.contentLbl setHidden:NO];
        [self.LotNumberLabel setHidden:NO];
        [followNumArray removeAllObjects];
    }
    
    self.IssueNumLabel.text = [NSString stringWithFormat:@"共追号%d期",[[cellvalue objectForKey:@"IssueNum"]intValue]];
    self.BuyedIssueNumLabel.text=[NSString stringWithFormat:@"已完成%d期",[[cellvalue objectForKey:@"BuyedIssueNum"] intValue]];
    self.chaseStateLabel.text = [cellvalue objectForKey:@"ChaseState"];
    if ([self.chaseStateLabel.text isEqualToString:@"进行中"]) {
        stopbutton.hidden = NO;
    }else {
        stopbutton.hidden = YES;
    }
    [listTable reloadData];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"FollowNumberDetail"];
    [MobClick event:@"UserCenter-zhuihaojilu-detail"];

    [self.contentLbl setHidden:YES];
    [self.LotNumberLabel setHidden:YES];
    self.stopLbl.text = @"-";
    
    [self startQuery];
    [self reloadData];

}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"FollowNumberDetail"];
}
- (void)viewDidUnload
{
    [self setContentLbl:nil];
    [self setStopLbl:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
